package cn.itcast.web.servlet;

import cn.itcast.domian.User;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(name = "loginServlet", value = "/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     request.setCharacterEncoding("utf-8");

//  少了验证码

        HttpSession session = request.getSession();

        Map<String, String[]> map = request.getParameterMap();
        User  user=new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        UserService service = new UserServiceImpl();
     User loginUser=  service.login(user);
     if (loginUser!=null) {
         session.setAttribute("user", loginUser);
     response.sendRedirect(request.getContextPath()+"/index.jsp");
     }else{
         request.setAttribute("login_msg","用户或密码错误");
     request.getRequestDispatcher("/login.jsp").forward(request,response);
     }
    }
}
